package m.store.action;

import com.alibaba.fastjson.JSONObject;
import m.base.action.BaseAction;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.*;
import m.html.VueCollectResult;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.element.other.DisplayItem;
import m.html.form.*;
import m.html.list.*;
import m.store.model.*;
import m.store.service.GoodsOutRecordService;
import m.store.service.GoodsStockRecordService;
import m.store.util.ColorUtil;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.NumberUtil;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;

@ActionMeta(name = "store/goodsStockRecord")
public class GoodsStockRecordAction extends BaseAction {
    private GoodsStockRecord model;
    @RequestMeta(logTitle = "入库明细",logDescription = "保存退货信息")
    public JSONMessage saveRefund() throws Exception {
        getService(GoodsStockRecordService.class).saveRefund(model);
        return new JSONMessage(0,"退货成功，记录生效");
    }
    @RequestMeta(logTitle = "入库明细",logDescription = "删除退货信息")
    public JSONMessage deleteRefund() throws Exception {
        getService(GoodsStockRecordService.class).deleteRefund(model.getOid());
        return new JSONMessage(0,"删除成功");
    }
    /*
     * 编辑undefined
     */
    public VueResult inputRefund() throws Exception {
        if(null!=model&&!ObjectUtil.isEmptyOid(model.getBackRecord())){
            model.setBackRecord(ModelQueryList.getModel(model.getBackRecord(),"*","goods.name"));
            //model.setStockNum(model.getBackRecord().getSurplusNum());
            model.setPrice(model.getBackRecord().getPreferentialPrice());
            model.setPreferential(0d);
            model.setStockAmount(0d);
        }else{
            throw new MException(this.getClass(),"参数错误");
        }
        ModelForm form = new ModelForm("录入退货");
        form.addItem(
            FormHtml.inputStyle("商品名称", "{{model.backRecord.goods.name}}").setSpan(3),
            FormHtml.inputStyle("数量", "{{formatNumber(model.backRecord.stockNum,'#,##0')}}"),
            FormHtml.inputStyle("可退数量", "{{formatNumber(model.backRecord.surplusNum,'#,##0.00')}}"),
            FormInput.number("退货数量", "model.stockNum").setPlaceholder("请输入退货数量").setRequired(true),
            FormHtml.inputStyle("单价", "{{formatNumber(model.backRecord.price,'#,##0.00')}}"),
            FormHtml.inputStyle("优惠单价", "{{formatNumber(model.backRecord.preferentialPrice,'#,##0.00')}}"),
            FormInput.number("退货单价", "model.price").setPlaceholder("请输入退货单价").setRequired(true),
            FormHtml.inputStyle("总优惠", "{{formatNumber(model.backRecord.preferential,'#,##0.00')}}"),
            FormHtml.inputStyle("金额", "{{formatNumber(model.backRecord.stockAmount,'#,##0.00')}}"),
            FormHtml.inputStyle("退货金额", "{{formatNumber(model.stockAmount,'#,##0.00')}}").setRequired(true),
            FormInput.textarea("退货备注","model.remark").setSpan(3).setPlaceholder("请输入退货备注")
        )
        .addData("model",model)
        .addButton(
            FormButton.pri("确认退货","saveRefund").setConfirm("确定要退货吗？")
        )
        .addWatch("model.stockNum","this.model.stockAmount=this.model.stockNum*this.model.price;")
        .addWatch("model.price","this.model.stockAmount=this.model.stockNum*this.model.price;")
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("saveRefund",actionUrl("saveRefund"),"{model:this.model}")
                .success("backFlag")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form);
    }

    /*
     * 入库明细列表
     */
    public VueResult recordList() throws Exception {
        boolean refund="refund".equals(getParamsValue("oper"));
        boolean isStock= !StockInfo.Type_Refund.equals(getParamsValue("stock.type"));
        VueListResult result=getVueListResult(isStock?"入库明细":"退货明细", GoodsStockRecord.class,actionUrl("recordList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addQueryFields("surplusNum");
        result.addCol(toTextColumn("仓库", "repository.oid", 100, true).setDictType(RepositoryInfo.class,PowerUtil.getSessionStoreOid()));
        result.addCol(toTextColumn("类型", "goods.typeName", 100, true));
        result.addCol(toLinkColumn("商品名称", "goods.name", 200, true,
            new ListEvent("page/store/storeGoods.js", EventType.MODAL,600)
                .addParam("oid","goods.oid")
        ));
        result.addCol(toNumberColumn("单价", "price", 100, true).setGroupTitle(isStock?"入库":"退货").setCount(ListCount.NONE));
        result.addCol(toIntegerColumn("数量", "stockNum", 100, true).setGroupTitle(isStock?"入库":"退货"));
        result.addCol(toNumberColumn(isStock?"总优惠":"总扣减", "preferential", 100, true));
        result.addCol(toNumberColumn("单价", "preferentialPrice", 100, true).setGroupTitle(isStock?"库存":"退款").setCount(ListCount.NONE));
        result.addCol(toNumberColumn("金额", "stockAmount", 100, true).setGroupTitle(isStock?"库存":"退款"));
        result.addCol(toTextColumn("备注","remark",100,true));
        if(refund){
            result.addCol(toSpaceColumn("操作", 100,
                ListElement.test("record.surplusNum>0",
                    ListButton.modal("录入退货", ButtonType.WARN,actionUrl("inputRefund"),1000,SuccessMethod.REFRESH)
                        .addParam("model.backRecord.oid","oid")
                ),
                ListElement.test("record.stockNum<0",
                    ListButton.ajax("删除退货", ButtonType.ERROR,actionUrl("deleteRefund"),SuccessMethod.REFRESH)
                        .addParam("model.oid","oid").setConfirm("确定要删除退货吗？")
                )
            ).setFixed(Align.RIGHT));
        }
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("stock.oid",getParamsValue("stock.oid")));
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        result.addOrder(QueryOrder.asc("oid"));
        return result;
    }
    public VueResult refundRecordList() throws Exception {
        VueListResult result=getVueListResult("退货入库明细", GoodsStockRecord.class,actionUrl("refundRecordList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addCol(toLinkColumn("入库单号", "stock.orderNo", 120, true,
            new ListEvent(actionUrl(StockInfoAction.class,"toView"), EventType.MODAL,1200)
                .addParam("model.oid","stock.oid")
        ));
        result.addCol(toDateColumn("入库日期", "stock.stockDate", 100, true));
        result.addCol(toTextColumn("仓库", "repository.oid", 100, true).setDictType(RepositoryInfo.class,PowerUtil.getSessionStoreOid()));
        result.addCol(toTextColumn("类型", "goods.typeName", 100, true));
        result.addCol(toLinkColumn("商品名称", "goods.name", 200, true,
            new ListEvent("page/store/storeGoods.js", EventType.MODAL,600)
                .addParam("oid","goods.oid")
        ));
        result.addCol(toNumberColumn("单价", "price", 100, true).setGroupTitle("退货").setCount(ListCount.NONE));
        result.addCol(toIntegerColumn("数量", "stockNum", 100, true).setGroupTitle("退货"));
        result.addCol(toNumberColumn("总扣减", "preferential", 100, true));
        result.addCol(toNumberColumn("单价", "preferentialPrice", 100, true).setGroupTitle("退款").setCount(ListCount.NONE));
        result.addCol(toNumberColumn("金额", "stockAmount", 100, true).setGroupTitle("退款"));
        result.addCol(toTextColumn("备注","remark",100,true));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("stock.refundSale.oid",getParamsValue("stock.refundSale.oid")));
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        result.addOrder(QueryOrder.asc("oid"));
        return result;
    }
    private ListColumn getTypeColumn(){
        String dict="m.store.model.StockInfo!type";
        return toElementColumn("类型", "stock.type", 100,
            ListElement.tag(dict, ColorUtil.getStockType(),false)
        ).setAlign(Align.CENTER).setFilter(true).setDictType(dict);
    }
    public VueResult selectStockList() throws Exception {
        String virtualTab=getParamsValue("virtualTab");
        String selected=getParamsValue("selected","");
        VueListResult result=getVueListResult("选择入库明细", GoodsStockRecord.class,actionUrl("selectStockList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.addQueryFields("oid","goods.oid");
        result.addCol(toIndexColumn());
        if(StringUtil.notSpace(virtualTab)) {
            result.setCustomTabs("virtualTab", DisplayItem.to("A", "正常库存", "B", "虚拟库存", "C", "服务项目"));
        }
        if(StringUtil.noSpace(virtualTab).equals("C")){
            result.setMergeCellsInfo(1,2);
            result.addCol(toTextColumn("分类", "goods.storeType.oid", 100, true).setDictType(StoreType.class,PowerUtil.getSessionStoreOid()));
            result.addCol(toTextColumn("类型", "goods.typeName", 100, true));
            result.addCol(toLinkColumn("服务名称", "goods.name", 200, true,
                    new ListEvent("page/store/storeGoods.js", EventType.MODAL,600)
                            .addParam("oid","goods.oid")
            ));
            result.addCol(toNumberColumn("报价","goods.offerPrice",100,true).setCount(ListCount.NONE));
            result.addCondition(QueryCondition.eq("stock.type",StockInfo.Type_Server));
            result.addCondition(QueryCondition.eq("stock.status",OrderModel.Status_Done));
            result.addOrder(
                QueryOrder.asc("goods.storeType.oid"),
                QueryOrder.asc("goods.typeName")
            );
        }else if(StringUtil.noSpace(virtualTab).equals("B")){
            result.setMergeCellsInfo(1,3);
            result.addCol(toTextColumn("分类", "goods.storeType.oid", 100, true).setDictType(StoreType.class,PowerUtil.getSessionStoreOid()));
            result.addCol(toLinkColumn("可调货客户", "stock.guest.name", 150, true,
                new ListEvent(actionUrl(GuestInfoAction.class,"toView"), EventType.MODAL,1300)
                    .addParam("model.oid","stock.guest.oid")
            ));
            result.addCol(toTextColumn("类型", "goods.typeName", 100, true));
            result.addCol(toLinkColumn("可调商品", "goods.name", 200, true,
                new ListEvent("page/store/storeGoods.js", EventType.MODAL,600)
                    .addParam("oid","goods.oid")
            ));
            result.addCol(toNumberColumn("报价","goods.offerPrice",100,true).setCount(ListCount.NONE));
            result.addCondition(QueryCondition.eq("stock.type",StockInfo.Type_Virtual));
            result.addCondition(QueryCondition.eq("stock.status",OrderModel.Status_Register));
            result.addOrder(
                QueryOrder.asc("goods.storeType.oid"),
                QueryOrder.asc("stock.guest.name"),
                QueryOrder.asc("goods.typeName")
            );
        }else{
            result.setMergeCellsInfo(1,5);
            result.addCol(toTextColumn("分类", "goods.storeType.oid", 100, true).setDictType(StoreType.class,PowerUtil.getSessionStoreOid()));
            result.addCol(toTextColumn("仓库", "repository.oid", 100, true).setDictType(RepositoryInfo.class,PowerUtil.getSessionStoreOid()));
            result.addCol(toLinkColumn("入库客户", "stock.guest.name", 100, true,
                new ListEvent(actionUrl(GuestInfoAction.class,"toView"), EventType.MODAL,1300)
                    .addParam("model.oid","stock.guest.oid")
            ));
            result.addCol(toLinkColumn("商品名称", "goods.name", 200, true,
                new ListEvent("page/store/storeGoods.js", EventType.MODAL,600)
                    .addParam("oid","goods.oid")
            ));
            result.addCol(toNumberColumn("报价","goods.offerPrice",100,true).setCount(ListCount.NONE));
            result.addCol(toLinkColumn("入库单号", "stock.orderNo", 120, true,
                new ListEvent(actionUrl(StockInfoAction.class,"toView"), EventType.MODAL,1200)
                    .addParam("model.oid","stock.oid")
            ));
            result.addCol(toNumberColumn("单价", "price", 80, true).setGroupTitle("入库").setCount(ListCount.NONE));
            result.addCol(toIntegerColumn("数量", "stockNum", 80, true).setGroupTitle("入库"));
            result.addCol(toNumberColumn("总优惠", "preferential", 80, true).setGroupTitle("入库"));
            result.addCol(toNumberColumn("单价", "preferentialPrice", 100, true).setGroupTitle("库存").setCount(ListCount.NONE).setFixed(Align.RIGHT));
            result.addCol(toIntegerColumn("余量", "surplusNum", 100, true).setGroupTitle("库存").setFixed(Align.RIGHT));
            result.addCondition(QueryCondition.gt("surplusNum", 0));
            result.addCondition(QueryCondition.eq("stock.status",OrderModel.Status_Done));
            result.addOrder(
                QueryOrder.asc("goods.storeType.sort"),
                QueryOrder.asc("repository.oid"),
                QueryOrder.asc("stock.guest.name"),
                QueryOrder.asc("goods.name")
            );
        }
        result.addCol(toSpaceColumn("操作", 100,
            ListElement.test("record.oid!='"+selected+"'",
                ListButton.back("选择", ButtonType.PRIMARY)
                    .addParam("","")
            ),
            ListElement.elseOther(ListElement.tag("已选",""))
        ).setFixed(Align.RIGHT));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addSearch(ListSearch.field("入库oid","stock.oid",SearchType.HIDDEN_EQ));
        result.addSearch(ListSearch.field("商品oid","goods.oid",SearchType.HIDDEN_EQ));
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        return result;
    }

    /**
     * 商品、客户、台账
     */
    public VueResult goodsRecordList() throws Exception {
        VueListResult result=getVueListResult("入库商品明细台账", GoodsStockRecord.class,actionUrl("goodsRecordList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addCol(getTypeColumn());
        result.addCol(toLinkColumn("入库单号", "stock.orderNo", 120, true,
            new ListEvent(actionUrl(StockInfoAction.class,"toView"), EventType.MODAL,1200)
                .addParam("model.oid","stock.oid")
        ));
        result.addCol(toTextColumn("仓库", "repository.oid", 100, true).setDictType(RepositoryInfo.class,PowerUtil.getSessionStoreOid()));
        if(StringUtil.notSpace(getParamsValue("goodsOid"))) {
            result.hideHead();
            result.addCol(toTextColumn("入库客户", "stock.guest.name", 150, true));
            result.addCondition(QueryCondition.eq("goods.oid", getParamsValue("goodsOid")));
        }else if(StringUtil.notSpace(getParamsValue("guestOid"))){
            result.hideHead();
            result.addCol(toTextColumn("商品名称", "goods.name", 150, true));
            result.addCondition(QueryCondition.eq("stock.guest.oid", getParamsValue("guestOid")));
        }else{
            result.addCol(toTextColumn("入库客户", "stock.guest.name", 150, true));
            result.addCol(toTextColumn("商品名称", "goods.name", 150, true));
        }
        result.addCol(toDateColumn("入库日期", "stock.stockDate", 100, true));
        result.addCol(toNumberColumn("单价", "price", 100, true).setGroupTitle("入库").setCount(ListCount.NONE));
        result.addCol(toIntegerColumn("数量", "stockNum", 100, true).setGroupTitle("入库"));
        result.addCol(toNumberColumn("总优惠", "preferential", 100, true));
        result.addCol(toNumberColumn("单价", "preferentialPrice", 100, true).setGroupTitle("库存").setCount(ListCount.NONE));
        result.addCol(toNumberColumn("金额", "stockAmount", 100, true).setGroupTitle("库存"));
        result.addCol(toIntegerColumn("出库数量", "saleNum", 100, true));
        result.addCol(toIntegerColumn("数量", "surplusNum", 100, true).setGroupTitle("剩余"));
        result.addCol(toNumberColumn("金额", "surplusAmount", 100, true).setGroupTitle("剩余"));
        result.addCol(toTextColumn("备注","remark",100,true));
        result.addCol(toTextColumn("登记人", "stock.inputUser.realname", 100, true));
        result.addCol(toDateTimeColumn("录入时间", "stock.inputDate", 130, true));
        result.addCol(toTextColumn("审核人", "stock.checkUser.realname", 100, true));
        result.addCol(toDateTimeColumn("审核时间", "stock.checkDate", 130, true));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("stock.status", OrderModel.Status_Done));
        result.addCondition(QueryCondition.eq("store.oid",PowerUtil.getSessionStoreOid()));
        result.addCondition(QueryCondition.not(QueryCondition.in("stock.type",StockInfo.Type_Virtual,StockInfo.Type_Server)));
        result.addOrder(QueryOrder.asc("oid"));
        return result;
    }
    public VueResult goodsRecordCollect() throws Exception {
        FromQueryList from=FromQueryList.fromGroup("a",
            ModelQueryList.instance(GoodsStockRecord.class,new String[0],null,
                QueryCondition.and(
                    QueryCondition.eq("store.oid",PowerUtil.getSessionStoreOid()),
                    QueryCondition.eq("stock.status",OrderModel.Status_Done),
                    QueryCondition.not(QueryCondition.in("stock.type",StockInfo.Type_Virtual,StockInfo.Type_Server))
                )
            )
        );
        VueCollectResult result=getVueCollectResult("入库记录汇总",from,actionUrl("goodsRecordCollect"));
        result.setFunction(LevelUtil.exportFunc(),LevelUtil.chartFunc());
        result.setHeight(-1);
        result.addCol(collectIndexColumn());
        result.addCol(collectTextColumn("账期月份","DATE_FORMAT(#{a.stock.stockDate},'%Y-%m') stockMonth",100,true));
        result.addCol(collectElementColumn("入库类型","#{a.stock.type} stockType",100,
            ListElement.tag("m.store.model.StockInfo!type", ColorUtil.getStockType(),false)).setFilter(true).setDictOption(StockInfo.class,"type"));
        result.addCol(collectDateColumn("入库日期","#{a.stock.stockDate} stockDate",100,true));
        result.addCol(collectTextColumn("进货客户","#{a.stock.guest.name} guestName",180,true));
        result.addCol(collectTextColumn("入库仓库","#{a.repository.oid} repositoryOid",100,true).setDictType(RepositoryInfo.class,PowerUtil.getSessionStoreOid()));
        result.addCol(collectTextColumn("入库商品","#{a.goods.name} goodsName",200,true));
        result.addCol(collectIntegerColumn("入库数量","SUM(#{a.stockNum}) stockNum",100,true));
        result.addCol(collectNumberColumn("总优惠","SUM(#{a.preferential}) preferential",100,true));
        result.addCol(collectNumberColumn("入库金额","SUM(#{a.stockAmount}) stockAmount",100,true));
        result.addCol(collectIntegerColumn("出库数量", "SUM(#{a.saleNum}) saleNum", 100, true));
        result.addCol(collectIntegerColumn("剩余数量", "SUM(#{a.surplusNum}) surplusNum", 100, true));
        result.addCol(collectNumberColumn("剩余金额", "SUM(#{a.surplusAmount}) surplusAmount", 100, true));
        return result;
    }

    public GoodsStockRecord getModel() {
        return model;
    }

    public void setModel(GoodsStockRecord model) {
        this.model = model;
    }
}
